﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using ThoughtWorks.QRCode.Codec;

namespace Alphacat.Model
{
    class QRCode
    {
        public static Bitmap ShowQRCodeBitmap(string content)
        {
            QRCodeEncoder encoder = new QRCodeEncoder();
            encoder.QRCodeBackgroundColor = Color.White;
            encoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            encoder.QRCodeScale = 5;
            encoder.QRCodeVersion = 0;
            encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            Bitmap bitmap = encoder.Encode(content, Encoding.UTF8);

            // 空白图片
            Bitmap blank = new Bitmap("blank.jpg");
            Graphics g = Graphics.FromImage(blank);

            // 把生成的二维码画在上面
            g.DrawImage(bitmap, new PointF(21, 10));

            // 加文字
            content = System.Text.RegularExpressions.Regex.Replace(content, @"(\w{4})", "$1 ");
            Font font = new Font("Consolas", 10);
            SolidBrush sbrush = new SolidBrush(Color.Black);
            g.DrawString(content, font, sbrush, new PointF(10.3f, 146));

            return blank;
        }

        public static byte[] GetQRCodeBytes(string content)
        {
            Bitmap bitmap = ShowQRCodeBitmap(content);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Png);
            byte[] bytes = ms.GetBuffer();
            ms.Close();
            return bytes;
        }

        public static void SaveBitmapPngFile(string content)
        {
            Bitmap bitmap = ShowQRCodeBitmap(content);

            string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/AlphaCat/code.png";
            bitmap.Save(docPath);
        }
    }
}
